import "./reset.css";
import dayjs from "dayjs";
import editForm from "../form/index.vue";
import editField from "../form/desigApp.vue";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import { ElMessage } from "element-plus";
import { copyApplication } from "@/api/application";
import { type PaginationProps } from "@pureadmin/table";
import type {
  FormItemProps,
  formTable
  //RoleFormItemProps
} from "./types";
import { getKeyList } from "@pureadmin/utils";
import {
  //getRoleIds,
  getTableClassList
  //getTableInfoList,
  //saveForm,
  //delFormByIDS,
  //generateForm
  //getAllRoleList
} from "@/api/metaTable";

import { getAppList, saveApp, delApp } from "@/api/application";
import {
  // ElForm,
  // ElInput,
  // ElFormItem,
  //ElProgress,
  ElMessageBox //,gitp
  //formItemProps
} from "element-plus";
import {
  type Ref,
  h,
  ref,
  toRaw,
  computed,
  reactive,
  onMounted,
  watch,
  nextTick
} from "vue";
import { useRouter } from "vue-router";
import { useUserStoreHook } from "@/store/modules/user";

export function useUser(tableRef: Ref, treeRef: Ref) {
  const formRef = ref();
  const ruleFormRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const router = useRouter();
  // 上传头像信息
  //const avatarInfo = ref();
  const switchLoadMap = ref({});
  const { switchStyle } = usePublicHooks();
  const higherDeptOptions = ref();
  const treeData = ref([]);
  const treeLoading = ref(true);
  const selectedNum = ref(0);
  const userStore = useUserStoreHook();
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const form = reactive({
    // 左侧部门树的id
    deptId: 0,
    appName: "",
    isShow: "",
    onePage: pagination,
    sortName: "id",
    sort: false
  });
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "编号",
      prop: "id",
      width: 90,
      sortable: "custom"
    },
    {
      label: "应用图标",
      slot: "image",
      width: 90
    },
    {
      label: "应用名称",
      prop: "appName"
    },
    {
      label: "是否启用",
      prop: "isShow",
      minWidth: 90,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.isShow}
          active-value={1}
          inactive-value={0}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    {
      label: "应用范围",
      prop: "appRange"
    },
    {
      label: "机构代码",
      prop: "comID"
    },
    {
      label: "创建时间",
      minWidth: 90,
      prop: "addTime",
      formatter: ({ addTime }) => dayjs(addTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });

  //启用停用设置
  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 0 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.appName
      }</strong>应用吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        setTimeout(async () => {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          const Result = await saveApp(row);
          if (Result.isSuccess) {
            message("已成功修改用户状态", {
              type: "success"
            });
          } else {
            message(Result.msg, { type: "error" });
          }
        }, 300);
      })
      .catch(() => {
        row.isShow === 0 ? (row.isShow = 1) : (row.isShow = 0);
      });
  }

  //修改设置

  function handleUpdate() {
    console.log("row: ");
  }

  //远程排序
  function sortChange({ column }) {
    form.sort = column.order == "ascending" ? true : false;
    form.sortName = column.property;
    onSearch();
  }

  function handleDelete(row) {
    message(`您删除了用户编号为${row.id}的这条数据`, { type: "success" });
    onSearch();
  }

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
  }

  //分页选择
  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    form.onePage = pagination;
    onSearch();

    nextTick(() => {
      const selectedRowsString = localStorage.getItem("seleteditem");
      console.log(
        "handleCurrentChange: selectedRowsString=" + selectedRowsString
      );
      const selectedRows = JSON.parse(selectedRowsString); //selectedRowsString.split(",");
      dataList.value.forEach(row => {
        for (let i = 0; i < selectedRows.length; i++) {
          if (row.id == selectedRows[i]) {
            tableRef.value.getTableRef().toggleRowSelection(row, true);
            console.log("row[" + row.id + "]: " + JSON.stringify(row));
          }
        }
      });
    });
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
    console.log("handleSelectionChange: " + val);
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    const frmIDS = getKeyList(curSelected, "id");
    console.log("handleSelectionChange: " + JSON.stringify(frmIDS));

    localStorage.setItem("seleteditem", JSON.stringify(frmIDS));
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量删除 */
  async function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    const frmIDS = getKeyList(curSelected, "id");
    tableRef.value.getTableRef().clearSelection();
    const Result = await delApp({ ids: frmIDS });
    if (Result.isSuccess) {
      message(`已删除编号为 ${frmIDS} 的数据`, {
        type: "success"
      });
      onSearch();
    } else {
      message(Result.msg, { type: "error" });
    }
  }

  async function onSearch() {
    loading.value = true;
    //userStore.SET_APPINFOFOM(form);

    const Result = await getAppList(toRaw(form));

    if (Result.isSuccess) {
      dataList.value = Result.result;

      pagination.total = Result.onePage.total;
      pagination.pageSize = Result.onePage.pageSize;
      pagination.currentPage = Result.onePage.currentPage;
    } else {
      message(Result.msg, { type: "error" });
    }
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    //重视表单时需要清空缓存
    userStore.SET_APPINFOFOM(null);
    if (!formEl) return;
    formEl.resetFields();
    form.deptId = 0;
    treeRef.value.onTreeReset();
    onSearch();
  };

  function onTreeSelect({ id, selected }) {
    form.deptId = selected ? id : "";
    onSearch();
  }

  function formatHigherDeptOptions(treeList) {
    // 根据返回数据的status字段值判断追加是否禁用disabled字段，返回处理后的树结构，用于上级部门级联选择器的展示（实际开发中也是如此，不可能前端需要的每个字段后端都会返回，这时需要前端自行根据后端返回的某些字段做逻辑处理）
    if (!treeList || !treeList.length) return;
    const newTreeList = [];
    for (let i = 0; i < treeList.length; i++) {
      treeList[i].disabled = treeList[i].status === 0 ? true : false;
      formatHigherDeptOptions(treeList[i].children);
      newTreeList.push(treeList[i]);
    }
    return newTreeList;
  }

  //复制应用
  async function addnewapplication(row?: formTable) {
    const Result = await copyApplication({ appID: row.id });
    if (Result.isSuccess) {
      //ElMessage("复制成功");
      ElMessage({ message: "复制成功", type: "success" });
      onSearch();
    } else {
      ElMessage({ message: Result.msg, type: "error" });
    }
  }

  function openEditFieldDialog(row?: formTable) {
    if (row.appPath.indexOf("DataView") == -1) {
      addDialog({
        title: `应用设计-- [${row.appName}]`,
        props: {
          id: row?.id ?? 0,
          appName: row.appName
        },
        width: "80%",
        draggable: true,
        fullscreenIcon: true,
        closeOnClickModal: false,
        center: true,
        alignCenter: true,
        footerButtons: [
          {
            label: "添加模块",
            type: "primary",
            btnClick: () => {
              const FormRef = ruleFormRef.value;
              FormRef.addModel();
            }
          },
          {
            label: "保存设计",
            type: "success",
            btnClick: () => {
              const FormRef = ruleFormRef.value;
              FormRef.saveAppCon();
              //console.log();
            }
          }
        ],
        contentRenderer: () => h(editField, { ref: ruleFormRef }),
        closeCallBack: () => {
          //const dd = ruleFormRef.value.getRef();
          //const curData = options.props.formInline as FormItemProps;
          //if (curData.tableIsFaBu == 0) {
          //row.tableIsFaBu = 0;
          //}
          //console.log(curData, "dd");
          //console.log(curData, "curData");
        }
      });
    } else {
      userStore.SET_APPID(row.id);
      userStore.SET_APPNAME(row.appName);
      router.push("/application/DataView/index?id=123");
      //window.open(href, "_blank");
    }
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}应用`,
      props: {
        formInline: {
          higherDeptOptions: formatHigherDeptOptions(higherDeptOptions.value),
          appImage: row?.appImage ?? "",
          id: row?.id ?? 0,
          appName: row?.appName ?? "",
          appClass: row?.appClass ?? 0,
          appDescript: row?.appDescript ?? "",
          appSort: row?.appSort ?? 1,
          isShow: row?.isShow ?? 1,
          appRange: row?.appRange ?? "",
          addUser: row?.addUser ?? 0,
          addTime: row?.addTime,
          appType: row?.appType ?? 1,
          appPath: row?.appPath ?? "",
          isWebShow: row?.isWebShow ?? false,
          isPhoneShow: row?.isPhoneShow ?? false,
          isIndexShow: row?.isIndexShow ?? false
        }
      },
      width: "46%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了应用名称为${curData.appName}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            const subResult = await saveApp(curData);

            if (subResult.isSuccess) {
              chores();
            } else {
              message(subResult.msg, { type: "error" });
            }
          }
        });
      }
    });
  }

  //根据JSON表单生成数据库实体
  watch(form, () => {
    //监视查询参数是否有变化，如果有变化将保存到缓存
    userStore.SET_APPINFOFOM(form);
    //console.log(form);
  });
  onMounted(async () => {
    treeLoading.value = true;

    // 归属部门
    const Result = await getTableClassList({ classType: 2 });
    const currentRS = Result.result;
    higherDeptOptions.value = handleTree(
      currentRS,
      currentRS["id"],
      currentRS["parentID"],
      currentRS["id"]
    );
    treeData.value = handleTree(
      currentRS,
      currentRS["id"],
      currentRS["parentID"],
      currentRS["id"]
    );
    treeLoading.value = false;
    //如果本地应用缓存不为空，则用本地缓存
    if (userStore.appInfoForm != null) {
      form.onePage = userStore.appInfoForm.onePage;
      form.deptId = userStore.appInfoForm.deptId;
      form.appName = userStore.appInfoForm.appName;
      form.isShow = userStore.appInfoForm.isShow;
      form.sortName = userStore.appInfoForm.sortName;
      form.sort = userStore.appInfoForm.sort;
    }
    console.log("onMounted start invoke onSearch()");
    await onSearch();

    nextTick(() => {
      const selectedRowsString = localStorage.getItem("seleteditem");
      console.log("onMounted: selectedRowsString: " + selectedRowsString);
      const selectedRows = JSON.parse(selectedRowsString);
      dataList.value.forEach(row => {
        for (let i = 0; i < selectedRows.length; i++) {
          if (row.id == selectedRows[i]) {
            tableRef.value.getTableRef().toggleRowSelection(row, true);
            console.log("row[" + row.id + "]: " + JSON.stringify(row));
          }
        }
      });
    });
  });

  return {
    form,
    loading,
    columns,
    dataList,
    treeData,
    treeLoading,
    selectedNum,
    pagination,
    buttonClass,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    onTreeSelect,
    handleUpdate,
    handleDelete,
    sortChange,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange,
    openEditFieldDialog,
    addnewapplication
    //generateFormToTable
  };
}
